
# qiandao.py
import re
import requests
import urllib3
import json
import os
from datetime import datetime
import logging

# 禁用SSL警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 导入自定义的日志模块
from log_util import logger

# 全局配置
params = {"id": "dsu_paulsign:sign", "operation": "qiandao", "infloat": "1", "inajax": "1"}


def load_config_from_json():
    """从JSON文件加载配置"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    json_path = os.path.join(current_dir, "sign_config.json")

    with open(json_path, 'r', encoding='utf-8') as f:
        return json.load(f)


# 用户配置 - 从JSON文件读取
config_data = load_config_from_json()

users = {
    "ChinUp": {
        "header": config_data["ChinUp!"]["header"],
        "text": config_data["ChinUp!"]["text"]
    },
    "yisi7": {
        "header": config_data["奕思音乐七"]["header"],
        "text": config_data["奕思音乐七"]["text"]
    }
}


def sign_in(username, header, text):
    a = 0
    while a<=3:
        try:
            response = requests.post(
                url="https://www.easonfans.com/forum/plugin.php",
                headers=header,
                data=text,
                params=params,
                verify=False,
                timeout=10
            )

            if response.status_code == 200:
                if "签到成功" in response.text:
                    money_matches = re.findall(r'金钱 (\d+)', response.text)
                    if len(money_matches) >= 1:
                        first_money = money_matches[0]
                        if len(money_matches) >= 2:
                            second_money = money_matches[1]
                            logger.debug(f"{username}签到成功，签到金钱为{first_money}，额外金钱为{second_money}")
                            break
                        else:
                            logger.debug(f"{username}签到成功，签到金钱为{first_money}")
                            break
                elif "已经签到" in response.text:
                    logger.debug(f"{username}已签到")
                    break
                else:
                    a+=1
                    logger.debug(f"{username}第{a}次签到失败，{response.text}")

            else:
                a+=1
                logger.debug(f"{username}第{a}次签到请求失败，状态码: {response.status_code}")

        except requests.exceptions.RequestException as e:
            logger.debug(f"{username}签到请求异常: {e}")
        except Exception as e:
            logger.debug(f"{username}签到发生未知错误: {e}")


def main():
    """主函数"""
    for username, config in users.items():
        sign_in(username, config["header"], config["text"])


if __name__ == '__main__':
    main()